/**
 * 环面生成 - L5
 * @author lonphy
 * @version 0.1
 */
(function(L5) {
	"use strict";
	const X_BANDS = 30;
	const Y_BANDS = 30;

	class Torus {
		/**
		 * 平面构造
		 * @param aRadius {Number} 大圈半径
		 * @param bRadius {Number} 小圈半径
		 * @param aBrands {Number} 大圈切割份数
		 * @param bBrands {Number} 小圈切割份数
		 */
		constructor(aRadius,  bRadius, aBrands, bBrands) {
			this.ar = aRadius || 1;
			this.br = bRadius || 0.2;
			this.ab = aBrands || 10;
			this.bb = bBrands || 10;

			this.vertices = [];
			this.indices = [];
			this.materialLibrary = {};
			this.maters = [];
			this.create();
		}

		/**
		 * 构造平面
		 */
		create() {
			var vertex = this.vertices,
				indices = this.indices,
				ar = this.ar,
				br = this.br,
				ab = this.ab,
				bb = this.bb;

			for (let i = 0; i <= ab; ++i) {
				let t = i * Math.PI / ab;
				let st = Math.sin(t);
				let ct = Math.cos(t);

				for (let j = 0; j <= bb; ++j) {
					let phi = j * 2 * Math.PI / bb;
					let sp = Math.sin(phi);
					let cp = Math.cos(phi);

					var x = cp * st;
					var y = sp * st;
					var z = ct;

					var u = 1 - (j / bb);
					var v = 1 - (i / ab);

					vertex.push(br*x + ct*ar, br*y + st*ar, ar*z);	// position
					vertex.push(x, y, z);								// normal
					vertex.push(u, v, 0);								// uv and texture id
				}
			}

			let first, second;
			for (let i = 0; i < ab; ++i) {
				for (let j = 0; j < bb; ++j) {
					first = (i * (bb + 1)) + j;
					second = first + bb + 1;

					indices.push(first, second, first + 1, second, second + 1, first + 1);
				}
			}
		}

		setMaterial(name, mater) {
			this.materialLibrary[name] = mater;
			this.maters.push(name);
		}

		getMesh() {
			return {
				vertices: this.vertices.slice(),
				indices: this.indices.slice(),
				materialLibrary: this.materialLibrary,
				maters: this.maters.slice(),
				hasIndex: false
			};
		}
	}

	L5.Geometry.Torus = Torus;
})(window.L5);